<template>
  <view class="mall-page" :style="{ paddingTop: statusBarHeight + 'px' }">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">萌宠商城</text>
    </view>

    <!-- 商品分类 -->
    <scroll-view scroll-x class="category-scroll">
      <view class="category-list">
        <view v-for="(cat, index) in categories" 
              :key="index"
              :class="['category-item', currentCategory === index ? 'active' : '']"
              @tap="selectCategory(index)">
          <text class="category-text">{{ cat }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 养宠套装入口 -->
    <view class="pet-package-banner">
      <image src="/static/images/pet-package.png" 
             mode="aspectFill" 
             class="banner-image"></image>
      <view class="banner-overlay">
        <text class="banner-title">新手养宠套装</text>
        <text class="banner-subtitle">一站式解决方案 🎁</text>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="product-grid">
      <view class="product-card" v-for="(product, index) in products" :key="index" @tap="viewProduct(product)">
        <view class="product-image-wrapper">
          <image :src="product.image" mode="aspectFill" class="product-image"></image>
          <view v-if="product.tag" class="product-tag">
            <text class="iconfont">🤖</text>
            <text class="tag-text">{{ product.tag }}</text>
          </view>
        </view>
        <view class="product-info">
          <text class="product-name">{{ product.name }}</text>
          <view class="product-price-row">
            <view class="price-group">
              <text class="current-price">¥ {{ product.price }}</text>
              <text v-if="product.originalPrice" class="original-price">¥ {{ product.originalPrice }}</text>
            </view>
            <view class="add-cart-btn">
              <text class="iconfont">🛒</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import systemUtils from '../../common/utils/system.js'
import { loadProducts,loadProductCategory } from '@/api/Productapi.js'

const statusBarHeight = ref(0)
const currentCategory = ref(0)

const categories = ref(['全部商品'])

// 存储商品列表
const products = ref([])

// 页面加载时获取状态栏高度
onMounted(() => {
  statusBarHeight.value = systemUtils.getStatusBarHeight()
  loadProductsFromAPI() // 加载商品数据
  loadProductsCategoryFromAPI()
})

// 根据分类 ID 加载商品（前端 index → 后端 categoryId）
const selectCategory = (index) => {
  currentCategory.value = index
  loadProductsFromAPI(index)
}

// 替换原来的 uni.request 版本
const loadProductsFromAPI = async (categoryIndex = 0) => {
  uni.showLoading({ title: '加载中...' })

  try {
    // 调用封装的 API
    const result = await loadProducts(categoryIndex)

    uni.hideLoading()

    if (result !== null) {
      // 转换数据格式（根据后端字段映射）
      products.value = result.map(p => ({
        id: p.productId,
        name: p.name,
        price: p.price,
        originalPrice: p.originalPrice || null,
        image: p.image || '/static/images/default-product.png',
        tag: p.tag || null,
      }))
	  // console.log(products.value);
    } else {
      uni.showToast({ title: '加载失败', icon: 'error' })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({ title: '网络错误', icon: 'none', duration: 2000 })
  }
}

	
const loadProductsCategoryFromAPI = async () => {
	try {
		const result = await loadProductCategory()
		if(result !== null){
			categories.value.push(...result)
		}
	} catch (error) {
		uni.showToast({ title: '加载失败', icon: 'error' })
	}
}

const viewProduct = (product) => {
  console.log('View productId:', product.id)
  // 跳转到商品详情页面
  uni.navigateTo({
    url: `/pages/product-detail/product-detail?id=${product.id}`
  })
}
</script>

<style scoped>
.mall-page {
  min-height: 100vh;
  background-color: #F5F5F5;
  padding-bottom: 120rpx;
}

/* 页面标题 */
.page-header {
  background-color: #FFFFFF;
  padding: 32rpx;
  border-bottom: 1px solid #F0F0F0;
}

.page-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333333;
}

/* 分类滚动 */
.category-scroll {
  background-color: #FFFFFF;
  border-bottom: 1px solid #F0F0F0;
  white-space: nowrap;
}

.category-list {
  display: inline-flex;
  padding: 24rpx 32rpx;
  gap: 24rpx;
}

.category-item {
  padding: 16rpx 32rpx;
  background-color: #F5F5F5;
  border-radius: 999rpx;
  font-size: 28rpx;
  color: #666666;
  white-space: nowrap;
}

.category-item.active {
  background-color: #89CFF0;
  color: #FFFFFF;
}

/* 套装Banner */
.pet-package-banner {
  margin: 32rpx;
  border-radius: 24rpx;
  overflow: hidden;
  position: relative;
  height: 256rpx;
}

.banner-image {
  width: 100%;
  height: 100%;
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0,0,0,0.6), transparent);
  padding: 24rpx 32rpx;
  color: #FFFFFF;
}

.banner-title {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 8rpx;
}

.banner-subtitle {
  font-size: 24rpx;
}

/* 商品网格 */
.product-grid {
  padding: 0 32rpx;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24rpx;
}

.product-card {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.product-image-wrapper {
  position: relative;
  width: 100%;
  height: 320rpx;
}

.product-image {
  width: 100%;
  height: 100%;
}

.product-tag {
  position: absolute;
  top: 16rpx;
  left: 16rpx;
  background-color: rgba(137, 207, 240, 0.9);
  color: #FFFFFF;
  padding: 8rpx 16rpx;
  border-radius: 999rpx;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  gap: 4rpx;
}

.favorite-btn {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
}

.product-info {
  padding: 24rpx;
}

.product-name {
  font-size: 28rpx;
  color: #333333;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
  height: 78rpx;
  margin-bottom: 16rpx;
}

.product-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-group {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
}

.current-price {
  font-size: 32rpx;
  font-weight: bold;
  color: #89CFF0;
}

.original-price {
  font-size: 24rpx;
  color: #999999;
  text-decoration: line-through;
}

.add-cart-btn {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background-color: #89CFF0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}
</style>